package top.sdwu_top.kbase.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import top.sdwu_top.kbase.entity.KbaseAuthUser;
import top.sdwu_top.kbase.service.IKbaseRolePermissionService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component("rbacauthorityservice")
public class RbacAuthorityService {

    @Value("${admin.username:admin}")
    private String adminUsername;

    @Autowired
    IKbaseRolePermissionService permissionService;

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        log.info("=========================访问路径:{}", request.getRequestURI());

        System.out.println(authentication.getPrincipal());
        Object userInfo = authentication.getPrincipal();
        if (!(userInfo instanceof KbaseAuthUser)) {
            return false;
        }
        KbaseAuthUser user = (KbaseAuthUser) userInfo;
        if (Objects.equals(user.getUsername(), this.adminUsername)) {
            return true;
        }
        boolean hasPermission  = false;
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if (antPathMatcher.match("/login", request.getRequestURI())) {
            return true;
        }
        List<String> urls = permissionService.getUrlListByRoleId(user.getRoleId());
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        return hasPermission;
    }
}